<?php 
/**
 * 注册接口
 */
namespace api\home\controller;

use cmf\controller\RestBaseController;
use think\Config;
use PHPMailer\PHPMailer;
use think\Validate;
use think\Db;
use cmf\phpqrcode\QRcode;
use \phpqrcode\phpqrcode;
use wechatvi\WxCrypt;

class RegisterController extends RestBaseController{

	/**
	 * [sendMail 注册第一步]
	 * @return [type] [description]
	 */
	public function regisSendMail(){
        $validate = new Validate([
            'email' => 'require',
            'password' => 'require',
            'captcha' => 'require'
        ]);
        $validate->message([
            'email.require' => '邮箱不能为空!',
            'password.require' => '请输入您的密码!',
            'captcha.require' => '验证码不能为空！'
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        /**
         * 检测验证码
         */
        if (!cmf_captcha_check($data['captcha'])) {
            $this->error(lang('CAPTCHA_NOT_RIGHT'));
        }
        /**条件**/
        $userWhere = [];
        if (Validate::is($data['email'], 'email')) {
            $userWhere['email'] = $data['email'];
        } else {
            $this->error("请输入正确的邮箱格式！");
        }
        /**
         * 查看邮箱是否被注册
         */
        $mailCoent = Db::table('a_user')->where(['email'=>$data['email']])->find();
        if($mailCoent){
        	if($mailCoent['emailStatus'] == 1){//邮箱已经注册未验证
        		$this->success("邮件已发送,请查收邮件,前往激活账户!");
        	}else if($mailCoent['emailStatus'] == 2){//如果通过邮箱验证产
        		if($mailCoent['wachStatus'] == 1){ //查看是否绑定个人微信
        			$this->error("账户以激活,请前往绑定个人微信");
        		}else{
        			$this->error('此邮箱已被注册!');
        		}
        	}

        }

		/**
		 * [$mail 邮件限制每天只能发送5封]
		 * @var PHPMailer
		 */
		$mail = new PHPMailer();
		$mail->Host = Config::get('Host');
		$mail->SMTPAuth = Config::get('SMTPAuth');
		$mail->Username = Config::get('Username');
		$mail->Password = Config::get('Password');
		$mail->Port = Config::get('Port');
		$mail->SMTPSecure = Config::get('SMTPSecure');
		if(Config::get('isSMTP')){
			$mail->IsSMTP();
		}		
		$mail->IsHTML(Config::get('IsHTML'));
		$mail->CharSet='utf-8';
		$mail->Encoding = "base64";
		$mail->SMTPDebug = Config::get('SMTPDebug');
		$mail->setFrom(Config::get('Username'));
		$mail->addAddress($data['email']);
		//注册地址
		$link = 'http://localhost:8380/#/login?step=3&email='.$data['email'].'&xtamp='.time().'&nonce='.md5($data['password']);
		$mail->Subject = '欢迎注册偶客账号,请点击或复制一下连接进行激活,连接30分钟有效。';
		$mail->msgHTML('<a href="'.$link.'">'.$link.'</a>');
		$mail->AltBody = '12312';
		if(!$mail->send()){
			$this->error('邮件发送失败！');
		}else{
			//存储用户信息
			Db::table('a_user')->insert(['email'=>$data['email'],'password'=>md5($data['password']),'addtime'=>date('Y-m-d H:i:s')]);
			$this->success('邮件已发送请前往注册!',$link);
		}
	}


	/**
	 * [regisActivation 邮件激活]
	 * @return [type] [description]
	 */
	public function regisActivation(){
		$data = $this->request->param();
		if(!$data){
			$this->error('参数有误!');	
		}
		$us = Db::table('a_user')->where(['email'=>$data['email']])->find();
		if(!$us){
			$this->error('请求错误！');	
		}
		if(md5($data['password']) != $us['password']){
			$this->error('密码错误!');
		}
		if($us['emailStatus'] == 2){
			$this->success('验证已通过！请前往绑定个人微信号！');
		}
		//修改邮箱激活状态
		$rq = Db::table('a_user')->where(['id'=>$us['id']])->update(['emailStatus'=>2]);
		if($rq){
			$this->success('验证通过!');
		}
		$this->error('验证失败!');
	}

	/**
	 * [qcode 获取二维码接口]
	 * @return [type] [description]
	 */
	public function qcode(){
		$data = $this->request->param();
		if(!isset($data['email'])){
			$this->error('缺少email!');
		}
		$mail = Db::table('a_user')->where(['email'=>$data['email']])->find();
		if(!$mail){
			$this->error('邮箱有误!');
		}
		$getUrl = $this->getticket($mail['id']);
        $this->success('success','https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.$getUrl['ticket']);
	}

	/**
	 * [getWxUserOpenid 返回access_token]
	 * @return [type] [description]
	 */
	public function getAccesstoken($appId,$appsecret){
		//获取公众号 access_token
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appId.'&secret='.$appsecret;
        $tokenData = post($url,'');
        $access_token = json_decode($tokenData,true);
        return $access_token['access_token'];
	}

	/**
	 * [getticket 获取二维码必要的参数]
	 * @return [type] [description]
	 */
	public function getticket($userId='0'){
		$access_token = $this->getAccesstoken(Config::get('Myappid'),Config::get('MyappSecret'));
		$url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" .$access_token . "";
		//生成二维码需要的参数
        $qrcode = '{"expire_seconds": 1800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": '.$userId.'}}}';
        $momo = json_encode($qrcode, true);
        $result = post($url, $qrcode);
        $rs = json_decode($result, true);
        return $rs;
	}

	/**
	 * [chickAuthorization 检测是否绑定公众号]
	 * @return [type] [description]
	 */
	public function chickAuthorization(){
		$data = $this->request->param();
		if(!isset($data['email'])){
			$this->error('缺少email!');
		}
		$data = Db::table('a_user')->where(['email'=>$data['email'],'wachStatus'=>2])->count();
		if($data > 0){
			$this->success('已关注!');	
		}
		$this->error('未关注!');
	}

	/**
	 * [getToken 用户扫码关注状况]
	 * @auth    董
	 * @version v1.0.0
	 * @date    2018-06-11
	 */
	public function getToken(){
		$file_in = file_get_contents('php://input');
		$arr = simplexml_load_string($file_in);
		if($arr->MsgType == 'event'){
			$userinfo = $this->getUserInfo($arr->FromUserName); //获取个人关注者信息
			if($arr->Event == 'subscribe'){ //用户没有关注->关注
				Db::table('a_user')->update([
					'id' => str_replace('qrscene_','',$arr->EventKey),
					'openid' => $arr->FromUserName,
					'wachStatus' => 2,
					'nickName' => $userinfo['nickname'],
					'headerimg' => $userinfo['headimgurl']
				]);
			}else if($arr->Event == 'SCAN'){ //用户关注->关注
				Db::table('a_user')->update([
					'id' => $arr->EventKey,
					'openid' => $arr->FromUserName,
					'wachStatus' => 2,
					'nickName' => $userinfo['nickname'],
					'headerimg' => $userinfo['headimgurl']
				]);
			}
		}
	}	

	/**
	 * [getUserInfo 获取微信用户个人信息]
	 * @return [type] [description]
	 */
	public function getUserInfo($openid){
		$access = getAccessToken(Config::get('Myappid'),Config::get('MyappSecret'));
		$url = 'https://api.weixin.qq.com/cgi-bin/user/info';
		$data['access_token'] = $access;
		$data['openid'] = $openid;
		$data['lang'] = 'zh_CN';
		$getUserInfo = post($url,$data);
		$userinfp = json_decode($getUserInfo,true);
		return $userinfp;
	}
}